(function ($) {
    function create($target) {
        var $searchbox = $('<span class="searchbox" style="height:20px;" />').width($target.width());
        var $searchboxText = $('<input class="searchbox-text" readonly />').width($target.width() - 20);
        var $searchboxBtn = $('<span class="searchbox-button" style="height: 20px;line-height: 20px;width: 20px;"></span>');
        $target.removeAttr("name").hide().after($searchbox);
        $searchbox.append($searchboxText).append($searchboxBtn);
        $target.$searchbox = $searchbox;
        $target.$searchboxText = $searchboxText;
        $target.$searchboxBtn = $searchboxBtn;

        //设置初始值
        setValue($target, $target.options.selected);
        $searchboxText.focus(function () {
            createWindow($target);
        });
        $searchboxBtn.click(function () {
            createWindow($target);
        });

        //初始方法
        initMethod($target);
        //储存
        saveData($target);
    }

    function initMethod($target) {
        $target.getText = function () {
            return getText($target);
        }
        $target.getValue = function () {
            return getValue($target);
        }
    }

    function saveData($target) {
        $target.data("searchWin", $target);
    }

    function getData($target) {
        return $target.data("searchWin");
    }

    //设置值
    function setValue($target, selected) {
        $(selected).each(function () {
            $target.$searchbox.append(createIds($target, this[$target.options.idField]));

            if ($target.$searchboxText.val() == "") {
                $target.$searchboxText.val(this[$target.options.textField]);
            } else {
                $target.$searchboxText.val([$target.$searchboxText.val(), this[$target.options.textField]].join(","));
            }
        });
    }

    function getValue($target) {
        return $target.$searchbox.find('[name="' + $target.options.inputName + '"]').val();
    }

    function clearValue($target) {
        $target.$searchbox.find('[name="' + $target.options.inputName + '"]').remove();
        $target.$searchboxText.val("");
    }

    function getText($target) {
        return $target.$searchboxText.val();
    }

    function setText($target, value) {
        return $target.$searchboxText.val(value);
    }

    function createIds($target, value) {
        return $('<input type="hidden" />').attr("name", $target.options.inputName).attr("value", value);
    }

    function createWindow($target) {
        var $dialogDiv = $("<div style='padding: 0;'></div>").appendTo('body');
        var $layout = $("<div class='easyui-layout' fit='true'></div>").appendTo($dialogDiv);
        var $north = $("<div region='north' style='30px'></div>").appendTo($layout);
        var $northToolbar = $(["<div id='abc' class='textcon'><table class='tb'>",
            "<tr><th>", $target.options.searchTitle, "：</th>",
            "<td><input type='text' class='input-text' style='width:150px;'/></td>",
            "<td style='padding-left:5px;'><input type='button' class='submit'/>",
            "</td></tr></table></div>"].join("")).appendTo($north);

        var $center = $(["<div region='center'></div>"].join("")).appendTo($layout);
        var $centerTable = $("<table></table>").appendTo($center);
        var $south = $(["<div region='south' style='height: 100px;' split='true'></div>"].join("")).appendTo($layout);
        var $southTable = $("<table></table>").appendTo($south);
        $dialogDiv.dialog({
            iconCls: "icon-search",
            title: $target.options.title,
            width: $target.options.width,
            height: $target.options.height,
            cache: false,
            modal: true,
            buttons: [
                {
                    text: "确定",
                    handler: function () {
                        confirm($target);
                    }
                },
                {
                    text: "取消",
                    handler: function () {
                        close($target);
                    }
                }
            ],
            onClose: function () {
                destroy($target);
            }
        });
        $layout.layout();
        $target.$dialogDiv = $dialogDiv;
        $target.$centerTable = createCenterTable($centerTable, $target);
        $target.$southTable = createSouthTable($southTable, $target);

        //绑定按钮事件
        $northToolbar.find("input:button").click(function () {
            search($target, $northToolbar);
        });
        //绑定上下左右
        $northToolbar.find("input:text").keydown(function (e) {
            if ($.inArray(e.which, [27, 32, 38, 40]) > -1) {
                var bof = -1;
                var eof = $centerTable.datagrid("getData").total;
                var selected = $centerTable.datagrid("getSelected");
                var selectedIndex = selected ? $centerTable.datagrid("getRowIndex", selected) : bof;
            }
            switch (e.which) {
                case 38:    //上
                    if (--selectedIndex <= bof) {
                        $centerTable.datagrid("selectRow", eof - 1);
                    } else {
                        $centerTable.datagrid("selectRow", selectedIndex);
                    }
                    break;
                case 40:
                    if (++selectedIndex >= eof) {
                        $centerTable.datagrid("selectRow", bof + 1);
                    } else {
                        $centerTable.datagrid("selectRow", selectedIndex);
                    }
                    break;
                case 32:
                    if (selected)
                        centerTableSelect($target, selected);
                    break;
                case 27:
                    close($target);
            }
        });
        $northToolbar.find("input:text").focus();
    }

    function confirm($target) {
        var rows = $target.$southTable.datagrid("getRows");
        $target.options.selected = rows;
        clearValue($target);
        setValue($target, rows);
        //响应回调
        if ($target.options.callback && $.isFunction($target.options.callback)) {
            $target.options.callback($target, rows);
        }
        close($target);
    }

    function close($target) {
        $target.$dialogDiv.dialog("close");
    }

    function destroy($target) {
        $target.$dialogDiv.remove();
    }

    function search($target, $northToolbar) {
        $target.$centerTable.datagrid("unselectAll");
        var params = {};
        params[$target.options.textField] = $northToolbar.find("input:text").val();
        $target.$centerTable.datagrid({url: $target.options.url, queryParams: params});
    }

    function createCenterTable($container, $target) {
        var options = $target.options;
        var gridOptions = {
            url: options.autoload ? options.url:"",
            idField: options.idField,
            singleSelect: true,
            fit: true,
            fitColumns: true,
            pagination: options.pagination,
            rownumbers: true,
            collapsible: false,//是否可折叠的
            columns: options.columns,
            pageSize: 10,//每页显示的记录条数，默认为10
            onClickRow: function (rowIndex, rowData) {
                centerTableSelect($target, rowData);
            }
        };
        return $container.datagrid(gridOptions);
    }

    function centerTableSelect($target, rowData) {
        var options = $target.options;
        if (options.multiple) {
            if ($target.$southTable.datagrid("getRowIndex", rowData[$target.options.idField]) == -1) {
                $target.$southTable.datagrid("appendRow", rowData);
                $target.$southTable.datagrid("selectRecord",rowData[$target.options.idField]);
            }
        } else {
            $target.$southTable.datagrid("loadData", []);
            $target.$southTable.datagrid("appendRow", rowData);
            $target.$southTable.datagrid("selectRecord",rowData[$target.options.idField]);
        }
    }

    function createSouthTable($container, $target) {
        var options = $target.options;
        var gridOptions = {
            data: $.extend([], options.selected),
            idField: options.idField,
            singleSelect: true,
            fit: true,
            rownumbers: true,
            fitColumns: true,
            columns: options.columns,
            onDblClickRow: function (rowIndex) {
                $(this).datagrid("deleteRow", rowIndex);
            }
        };
        return $container.datagrid(gridOptions);
    }

    $.fn.searchWin = function (options) {
        if (getData($(this))) {
            return getData($(this));
        }

        $(this).each(function () {
            var $target = $.extend($(this), {
                options: $.extend({}, $.fn.searchWin.defaults, options || {}, {inputName: $(this).attr("name")})
            });
            create($target);
        })
    };


    $.fn.searchWin.defaults = {
        title: "弹出框标题",
        searchTitle: "搜索标题",
        width: 600,
        height: 500,
        multiple: false, //多选
        callback: null,
        columns: null,
        autoload:false,
        pagination:true
    }

})(jQuery);